<script setup>
import { computed, nextTick, onMounted, reactive, ref, watchEffect } from 'vue';
import data from "@/untils/address/states.json"
const formLabelWidth = '200px'
//  import dayjs from "dayjs"
import { ElMessage } from 'element-plus'
// import IconSelect from '@/components/IconSelect/index.vue'

import axios from 'axios';
import { getMenuList, addRoleData, EditRoleData, delMenuapi } from '../../api/api';
// import { fa } from 'element-plus/es/locales.mjs';
let formRef = ref(null)
let props = defineProps({
    dialogFormVisible: Boolean,
    formlist: Object,
    changeType: String,
    tableData: Array,
})
let menulist = ref([{
    "menuId": 0,
}])
// 递归提取所有 menuId
// 定义一个函数来转换数组
function transformArray(originalArray) {
    return originalArray.map(parent => {
        // 创建一个新的父对象，仅保留 id
        let newParent = {
            roleId: parent.roleId
        };

        // 如果存在 children，进行转换
        if (parent.children && parent.children.length > 0) {
            // 映射 children 数组，仅保留每个子对象的 id
            newParent.children = parent.children.map(child => {
                return {
                    roleId: child.roleId
                };
            });
        } else {
            // 如果没有 children，可以设置为 null 或空数组，视需求而定
            newParent.children = [];
        }

        return newParent;
    });
}
// 递归提取所有选中的menuId
// 递归提取所有选中的menuId
function extractSelectedMenuIds(menus) {
    let selectedIds = [];

    if (!menus || !Array.isArray(menus)) return selectedIds;

    menus.forEach(menu => {
        // 如果当前菜单有roleId，说明被选中
        if (menu.roleId !== undefined && menu.roleId !== null) {
            selectedIds.push(menu.menuId);
        }

        // 递归处理子菜单
        if (menu.children && Array.isArray(menu.children)) {
            selectedIds = selectedIds.concat(extractSelectedMenuIds(menu.children));
        }
    });

    return selectedIds;
}
let defaultCheckedKeys = ref([])
let checkStrictly = ref(false)
let fullMenuData = ref([])
// ✅ 递归提取所有 menuId 并去重
function extractUniqueMenuIds(data) {
    console.log(data);

    const result = new Set();
    function traverse(node) {
        if (!node) return;
        if (node.menuId !== undefined) {
            result.add(node.menuId);
        }
        if (node.children && Array.isArray(node.children)) {
            for (const child of node.children) {
                traverse(child);
            }
        }
    }
    for (const item of data) {
        traverse(item);
    }
    return Array.from(result);
}
watchEffect(() => {

    if (props.dialogFormVisible) {

        // 1. 先加载菜单数据
        getMenuList().then(res => {
            console.log(res);
            fullMenuData.value = res.data || [];
            if (props.changeType == 'update') {
                const extractedIds = extractUniqueMenuIds(props.formlist.menus);
                nextTick(() => {
                        menuTreeRef.value.setCheckedKeys([]); 
                        setTimeout(() => {
                            extractedIds.forEach((item) => {
                                menuTreeRef.value.setChecked(item, true, false);
                            });
                        }, 10);
                });
            }

        });
    }
})
onMounted(() => {
})
const selected = (name) => {
    form.icon = name
}
// 自定义下拉菜单展开状态
const dropdownVisible = ref(false)
// 当前选中的菜单项
const selectedMenuItem = ref(null)
// 当前展开的子菜单项
const expandedSubmenu = ref(null)

// 处理菜单选择
const handleMenuSelect = (item) => {
    selectedMenuItem.value = item
    form.parentId = item.menuId
    dropdownVisible.value = false // 选择后关闭下拉框
}
// 切换子菜单展开状态
const toggleSubmenu = (item) => {
    if (expandedSubmenu.value === item.menuId) {
        expandedSubmenu.value = null // 如果已经展开，则收起
    } else {
        expandedSubmenu.value = item.menuId // 否则展开
    }
}
let emits = defineEmits(["close", 'update:formlist'])
function closedialog(formEl) {
    // // 再次点击清空inp的值
    if (!formEl) return
    formEl.resetFields()
    // // // 向父组件发送自定义事件
    emits("close")
}
let menuTreeRef = ref(null);
async function addsubmit(formEl) {
    if (props.formlist.roleName == "" || props.formlist.roleCode == "") {
        ElMessage.warning("Please fill in the required fields");
        return;
    }
    if (props.changeType == "add") {
        // 添加操作
        console.log(props.formlist, "新增数据");
        console.log(menuTreeRef.value);

        console.log(props.formlist.roleName);
        console.log(props.formlist.roleCode);
        console.log(props.formlist.menus);
        // 获取选中的菜单节点
        await nextTick();

        console.log(menuTreeRef.value);

        if (menuTreeRef.value) {
            const checkedNodes = menuTreeRef.value.getCheckedNodes();

            // 如果需要只获取 menuId 和 menuName，可以映射一下
            const selectedMenus = checkedNodes.map(node => ({
                menuId: node.menuId,
                menuName: node.menuName
            }));
            let mymenus = []
            selectedMenus.forEach(res => {
                mymenus.push(res.menuId)
            })
            let requestData = {
                roleName: props.formlist.roleName,
                roleCode: props.formlist.roleCode,
                menuIds: mymenus
            }
            console.log(requestData);
            let res = await addRoleData(requestData)
            console.log(res);
            if (res.code == 200) {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            }

        }


        emits("close")
    } else if (props.changeType == "update") {
        // //编辑操作
        console.log(props.formlist, "编辑数据");
        console.log(menuTreeRef.value);
        if (menuTreeRef.value) {
            const checkedNodes = menuTreeRef.value.getCheckedNodes();

            // 如果需要只获取 menuId 和 menuName，可以映射一下
            const selectedMenus = checkedNodes.map(node => ({
                menuId: node.menuId,
                menuName: node.menuName
            }));
            let mymenus = []
            selectedMenus.forEach(res => {
                mymenus.push(res.menuId)
            })
            let requestData = {
                roleId: props.formlist.roleId,
                roleName: props.formlist.roleName,
                roleCode: props.formlist.roleCode,
                menuIds: mymenus
            }
            console.log(requestData);
            let res = await EditRoleData(requestData)
            console.log(res);
            if (res.code == 200) {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            }

        }
        emits("close")
    }
}


// 取消按钮
const cancel = () => {
    open.value = false
    resetForm()
}


// 加载菜单树
const getMenuTree = () => {
    listMenu().then(response => {
        menuOptions.value = response.data
    })
}

// 树形选择器转换
const normalizer = node => {
    if (node.children && !node.children.length) {
        delete node.children
    }
    return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
    }
}
// const loadMenuNodes = async (node, resolve) => {
//     try {
//        let res = getMenuList()
//         resolve(res.data);  // 假设返回格式是 [{ id, menuName, children }]
//     } catch (error) {
//         console.error("加载菜单失败", error);
//         resolve([]);  // 失败时返回空数组
//     }
// };
const iconSearch = ref('')
const icons = [
    'user', 'Minus', "CirclePlus", "Loading", "Setting", "House", "UserFilled", "Avatar", "CircleCheck", "Setting", "Document", "Notification", "Setting", "PriceTag", "SetUp", "DataAnalysis", "Reading", "FolderOpened", "DocumentChecked", "ScaleToOriginal", "DocumentDelete"
]
// 计算属性，过滤图标
const filteredIcons = computed(() => {
    if (!iconSearch.value) return icons
    return icons.filter(icon =>
        icon.toLowerCase().includes(iconSearch.value.toLowerCase())
    )
})
// 处理图标选择
const handleIconSelect = (icon) => {
    props.formlist.icon = icon
    //   iconSearch.value = '' // 清空搜索框
}

// 监听form.icon变化，当外部修改时更新选中状态
watchEffect(() => {
    if (props.formlist.icon && !filteredIcons.value.includes(props.formlist.icon)) {
        // 如果当前图标不在列表中，可以添加到列表或做其他处理
        console.warn(`Icon ${props.formlist.icon} not found in the icon list`)
    }
})
let icondiv = ref(false)
const roleRules = {
    roleName: [
        { required: true, message: 'The roleName cannot be empty', trigger: 'blur' }
    ],
    roleCode: [
        { required: true, message: 'TheroleCode cannot be empty', trigger: 'blur' }
    ],
}
</script>
<template>
    <div class="editclass">
        <el-dialog :model-value="dialogFormVisible" style="padding: 20px;width: 580px;"
            :title="changeType == 'add' ? 'add' : 'edit'" @close="closedialog(formRef)">
            <el-form :model="formlist" ref="formRef" class="two-column-form" :rules="roleRules">
                <!-- 上级菜单 -->
                <!-- 自定义上级菜单下拉框 -->
                <!-- <el-form-item label="roleName" :label-width="formLabelWidth" prop="roleName">
                    <el-tree-select v-model="formlist.roleName" :data="menulist" :props="{
                        value: 'menuId',  // 指定节点的value字段
                        label: 'menuName', // 指定节点的label字段
                        children: 'children' // 指定子节点字段
                    }" node-key="menuId" :expand-on-click-node="false" :check-strictly="true" style="width: 240px" />
                </el-form-item>
                <el-form-item label="menu type" prop="menuType" style="margin-left: 60px;">
                    <el-radio-group v-model="formlist.menuType">
                        <el-radio :value="1">menu</el-radio>
                        <el-radio :value="2">button</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <!-- 角色名称 -->
                <el-form-item label="roleName" :label-width="formLabelWidth" prop="roleName">
                    <el-input v-model="formlist.roleName" autocomplete="off" placeholder="Please enter the roleName"
                        style="width: 200px;" maxlength="30" />
                </el-form-item>
                <!-- 角色编码 -->
                <el-form-item label="roleCode" :label-width="formLabelWidth" prop="roleCode">
                    <el-input v-model="formlist.roleCode" autocomplete="off" placeholder="Please enter the roleCode"
                        style="width: 200px;" maxlength="30" />
                </el-form-item>
                <!-- 菜单权限 -->
                <el-form-item label="Menu permissions" :label-width="formLabelWidth" prop="menus">
                    <!-- :load="loadMenuNodes"  :load="loadMenuNodes" -->
                    <el-tree ref="menuTreeRef" style="max-width: 600px" :data="fullMenuData" show-checkbox
                        node-key="menuId" :check-strictly="checkStrictly" :props="{
                            label: 'menuName',
                            children: 'children'
                        }" />
                </el-form-item>

            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closedialog(formRef)">cancel</el-button>
                    <el-button type="primary" @click="addsubmit(formRef)">
                        {{ changeType == "add" ? 'add' : 'edit' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>
<style lang="scss" scoped>
.two-column-form .form-row {
    display: flex;
    justify-content: space-between;
}

// .two-column-form .el-form-item {
//     // width: 48%;
// }

.address-container {
    display: flex;
    align-items: center;
}

/* 调整表单标签宽度 */
.two-column-form :deep(.el-form-item__label) {
    // width: 80px;
    text-align: right;
    padding-right: 12px;
}

/* 自定义下拉菜单样式 */
.custom-select {
    position: relative;
    width: 100%;

    .select-input {
        width: 180%;

        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 10px;
        height: 36px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        cursor: pointer;

        .el-icon {
            margin-left: 5px;
        }
    }

    .dropdown-menu {
        position: absolute;
        top: 100%;
        left: 0;
        // width: 190%;
        background-color: #fff;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        z-index: 1000;
        max-height: 300px;
        overflow-y: auto;

        .menu-item {
            padding: 8px 15px;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;

            &:hover {
                background-color: #f5f7fa;
            }

            &.is-selected {
                font-weight: bold;
            }

            .expand-icon {
                margin-left: 5px;
                transition: transform 0.3s;
            }
        }

        .submenu {
            padding-left: 20px;

            .submenu-item {
                padding: 6px 15px;
                cursor: pointer;

                &:hover {
                    background-color: #f5f7fa;
                }
            }
        }
    }
}

/* 响应式设计 - 小屏幕时变为单列 */
@media (max-width: 768px) {
    .two-column-form .form-row {
        flex-direction: column;

        .el-form-item {
            width: 100%;
        }
    }

    .address-container {
        flex-direction: column;
        align-items: flex-start;

        .el-select {
            width: 100% !important;
            margin-right: 0 !important;
            margin-bottom: 10px;
        }
    }
}

.menu-icon {
    width: 25px;
    height: 25px;
}

// .icon-selector {
//     width: 100%;
//     height: 200px;
//     overflow: scroll;
//     background-color: #fff;
//     border: 1px solid #ccc;
//     border-radius: 4px;
//     padding: 10px;
//     box-sizing: border-box;
// }

.search-container {
    display: flex;
    margin-bottom: 15px;
}

.search-input {
    flex: 1;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px 0 0 4px;
    font-size: 14px;
}

.search-button {
    width: 40px;
    height: 36px;
    background-color: #f5f5f5;
    border: 1px solid #ddd;
    border-left: none;
    border-radius: 0 4px 4px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}

.icons-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    // gap: 10px 50px;
}

.icon-item {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 40px;
}

.icon-text {
    font-size: 14px;
    color: #333;
    text-align: center;
    word-break: break-all;
}
</style>